package top.dingwen.io.treasure.es.web;

import lombok.extern.slf4j.Slf4j;
import org.dromara.easyes.core.kernel.EsWrappers;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import top.dingwen.io.treasure.es.constant.EsConstant;
import top.dingwen.io.treasure.es.exception.EsExceptionCode;
import top.dingwen.io.treasure.es.mapper.DocumentMapper;
import top.dingwen.io.treasure.es.model.Document;
import top.dingwen.io.treasure.webplus.result.Result;
import top.dingwen.io.treasure.webplus.web.controller.BaseViewController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * es默认API
 *
 * @author dingwen
 * @since 2024/12/17 09:30
 */
@RestController
@Slf4j
@RequestMapping("/ess")
@Valid
public class EsIndexController implements BaseViewController {

    @Resource
    private DocumentMapper documentMapper;

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        if (!documentMapper.existsIndex(EsConstant.D_INDEX)) {
            Boolean success = documentMapper.createIndex();
            Assert.isTrue(success, EsExceptionCode.ES_INDEX_CREATE.getMessage());
        }
    }

    /**
     * 获取文档信息
     *
     * @return {@link Result }<{@link Document }>
     */
    @GetMapping("/test/documents")
    public Result<List<Document>> fetchDocument() {
        List<Document> documents = EsWrappers
                .lambdaChainQuery(documentMapper)
                .list();
        return success(documents);
    }

    /**
     * 创建一个文档
     *
     * @param document 文档数据对象
     * @return {@link Result }<{@link Boolean }>
     */
    @PostMapping("/test/documents")
    public Result<Boolean> createDocument(@RequestBody Document document) {
        return genResult(documentMapper.insert(document));
    }
}
